﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using EnumKeys;
using Webapp;
namespace xundh.API.Daily
{
    /// <summary>
    ///Daily_Records 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://www.lansezhongjie.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]

    public class Daily_Records : BaseService
    {
        [WebMethod(EnableSession = true)]
        public ServiceStateKeys Add(int id, DateTime DailyDate, string Contents)
        {
            ///Session
            if (U == null) return ServiceStateKeys.TimeOut;
            ///参数处理
            Contents = Server.UrlDecode(Contents);

            xundh.BLL.Daily_Records bllDaily = new xundh.BLL.Daily_Records();
            xundh.Model.Daily_Records mDaily;
            if (id > 0)
            {
                mDaily = bllDaily.GetModel(id);
                //只能修改当天的日志
                if (StringUtil.GetShortDate(mDaily.DailyDate) !=
                  StringUtil.GetShortDate(DateTime.Now))
                {
                    return ServiceStateKeys.Fail;
                }
                //判断权限
                if (mDaily == null)
                {
                    return ServiceStateKeys.NoPermiss;
                }
                if (mDaily.AddUserId != U.UserId)
                {
                    return ServiceStateKeys.NoPermiss;
                }
                ///禁止重复书写
                ///看那一天有没有写过了
                using (DataSet ds = bllDaily.GetList("AddUserId=" + U.UserId + " AND DailyDate ='" + DailyDate + "' AND id<>" + id))
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        return ServiceStateKeys.Exists;
                    }
                }
            }
            else
            {
                //禁止重复书写
                ///看那一天有没有写过了
                using (DataSet ds = bllDaily.GetList("AddUserId=" + U.UserId + " AND DailyDate ='" + DailyDate + "'"))
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        return ServiceStateKeys.Exists;
                    }
                }
                //允许写几天前的日期
                int allowDays = SystemGetInt("Daily", "DailyDaysBeforeCountAllow");
                DateTime Today = DateTime.Today;
                if (Today.AddDays(-allowDays) > DailyDate) {
                    return ServiceStateKeys.Fail;
                }
                mDaily = new xundh.Model.Daily_Records();
                mDaily.AddUserId = U.UserId;
                mDaily.AddUserName = U.UserName;
                mDaily.AddDepartId = U.DepartId;
                mDaily.AddDepart = "";
                mDaily.AddTime = NOW;
                mDaily.AddIp = IP;
                mDaily.Type = "日报";
            }
            mDaily.OrganizatioinId = 1;
            mDaily.DailyDate = DailyDate;
            mDaily.Contents = Contents;
            if (id > 0)
                bllDaily.Update(mDaily);
            else
                id = bllDaily.Add(mDaily);
            //启动流程
            WF.WF_Items serviceWFItems = new WF.WF_Items();
            try
            {
                serviceWFItems.AddTemplateTitle(0, "日清审批", "", id, "id");
            }
            catch (Exception)
            {
                bllDaily.Delete(id);
                return ServiceStateKeys.Fail;
            }
            return ServiceStateKeys.Success;
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public JsonTable GetLists(int page, int rows)
        {
            if (U == null) return null;
            xundh.BLL.Daily_Records bll = new xundh.BLL.Daily_Records();
            string Contents = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["Contents"]));
            string txtEndDate = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["txtEndDate"]));
            string txtBeginDate = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["txtBeginDate"]));
            int txtPosts = StringUtil.GetIntValue(HttpContext.Current.Request["txtPosts"]);
            int txtDeparts = StringUtil.GetIntValue(HttpContext.Current.Request["txtDeparts"]);
            int UserId = StringUtil.GetIntValue(HttpContext.Current.Request["UserId"]);
            string strWhere = "1=1";
            if (Contents != "")
                strWhere += " AND Contents LIKE '%" + Contents + "%'";
            if (txtEndDate != "")
                strWhere += " AND DailyDate<='" + txtEndDate + " 23:59:59'";
            if (txtBeginDate != "")
                strWhere += " AND DailyDate>='" + txtBeginDate + "'";
            if (txtDeparts > 0)
                strWhere += " AND AddDepartId=" + txtDeparts;
            if (UserId > 0)
                strWhere += " AND AddUserId=" + UserId;
            if (txtPosts > 0)
            {
                RBAC.RBAC_Users rbacUsers = new RBAC.RBAC_Users();
                List<Model.RBAC_Users> msPosts = rbacUsers.GetListsByPosts(txtPosts);
                string result = "";
                foreach (Model.RBAC_Users mTemp in msPosts)
                {
                    result = result.ItemAdd(mTemp.UserId);
                }
                if (result != "")
                    strWhere += " AND AddUserId in(" + result + ")";
                else
                    strWhere += " AND AddUserId=-1";
            }
            //权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(U.UserId, "工作日志", "查")) return null;
            //如果有查所有权限，可以查看部门及下级部门所有用户的日志
            if (serviceOperation.CheckResouceOperationLimit(U.UserId, "工作日志", "查所有"))
            { }
            else if (serviceOperation.CheckResouceOperationLimit(U.UserId, "工作日志", "查部门"))
            {
                Org.Org_Departs serviceDepart = new Org.Org_Departs();
                List<xundh.Model.Org_Departs> ms = serviceDepart.GetListsDepartsAndSons(U.DepartId ?? 0);
                string DepartIds = U.DepartId.ToString();
                foreach (xundh.Model.Org_Departs m in ms)
                {
                    DepartIds += "," + m.DepartId;
                }
                DepartIds = DepartIds.Trim(',');
                if (DepartIds != "") strWhere += " AND AddDepartId in(" + DepartIds + ")";
            }
            else
                strWhere += " AND AddUserId=" + U.UserId;
            JqGridHandler datagrid = new JqGridHandler(strWhere);
            int recordcount = bll.GetRecordCount(datagrid.StrWhere);
            datagrid.init(datagrid.StrWhere, page, recordcount, rows, "id", "desc");
            using (DataSet ds = bll.GetListByPage(strWhere, "id DESC", datagrid.StartIndex, datagrid.EndIndex))
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    ds.Tables[0].Rows[i]["Contents"] = StringUtil.CutHTML(Server.HtmlDecode(ds.Tables[0].Rows[i]["Contents"].ToString()).Replace("\"", "'").Replace("\r\n", "<br />").Replace("\n", "<br />"));
                }
                ds.AcceptChanges();
                return new JsonTable(ds.Tables[0], bll.GetRecordCount(strWhere));
            }
        }
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public xundh.Model.Daily_Records Query(int id)
        {
            if (U == null) return null;
            xundh.BLL.Daily_Records bll = new xundh.BLL.Daily_Records();
            xundh.Model.Daily_Records m = bll.GetModel(id);
            return m;
        }
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public ServiceStateKeys Delete(int id)
        {
            if (U == null) return ServiceStateKeys.TimeOut;
            //权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(U.UserId, "工作日志", "删")) return ServiceStateKeys.NoPermiss;

            xundh.BLL.Daily_Records bll = new xundh.BLL.Daily_Records();
            bll.Delete(id);
            return ServiceStateKeys.Success;
        }

    }
}